package net.chrisrichardson.ec2deployer.core

import org.jets3t.service.security.AWSCredentials
import org.jets3t.apps.synchronize.Synchronize
import org.jets3t.service.impl.rest.httpclient.RestS3Service


class S3Synchronizer {

    def MAX_RETRIES = 3
    
    AWSProperties awsProperties

    S3Synchronizer(AWSProperties awsProperties) {
        this.awsProperties = awsProperties
    }

    void uploadToS3(List filesOrDirectories, String bucketPrefix, String s3Bucket) {
        int retries = 0;
        while (true) {
            try {
                AWSCredentials awsCredentials = new AWSCredentials(
                        awsProperties.accessKey,
                        awsProperties.secretKey);
                Synchronize client = new Synchronize(
                        new RestS3Service(awsCredentials, "Synchronize/0.5.0", null),
                        true, true, false, false, false, false);
                client.run(awsProperties.accessKey + "." + makePrefixedBucket(bucketPrefix, s3Bucket), filesOrDirectories.collect {new File(it)}, "UP",
                        null, "PRIVATE");
                return;
            } catch (org.jets3t.service.S3ServiceException e) {
                retries = retries + 1;
                if (retries < MAX_RETRIES) {
                    Thread.sleep( 5 * 1000)
                } else
                    throw e
            }
        }

    }

    String makePrefixedBucket(String bucketPrefix, String s3Bucket) {
        bucketPrefix ? bucketPrefix + "-" + s3Bucket : s3Bucket
    }
    
    /**
     Make sure the S3 credentials used by Jets3t are in the right place
     */
    private copySynchronizeProperties(EC2Server server) {
        // JETS3T_ synchronize.sh has been modified to include /mnt in the classpath
        def properties = """
accesskey=${awsProperties.accessKey}
secretkey=${awsProperties.secretKey}
"""
        server.ssh("rm -f /mnt/synchronize.properties ; cat > /mnt/synchronize.properties; chmod 0600 /mnt/synchronize.properties", properties)
    }

    void downloadFromS3(EC2Server host, String bucketPrefix, String s3Bucket, String directory) {
        s3Bucket = awsProperties.accessKey + "." + makePrefixedBucket(bucketPrefix, s3Bucket)
        copySynchronizeProperties(host)
        host.ssh("/var/lib/jets3t-0.5.0/bin/synchronize.sh -q DOWN $s3Bucket $directory")
    }

}